package tebiang.zxy.demo2;

/**
 * @auther zhangxiaoyu
 * @date 2024/4/11 15:35
 * @description
 */
public class CustomList<T>{

    /**
     * 默认容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    private Object[] elements;

    private int size;

    public CustomList() {
        elements = new Object[DEFAULT_CAPACITY];
    }

    public CustomList(int initialCapacity) {
        elements = new Object[initialCapacity];
    }

    /**
     * 添加元素
     * @param element
     */
    public void add(T element) {
        ensureCapacity();
        elements[size++] = element;
    }

    /**
     * 删除元素
     * @param index
     */
    public void remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index out of bounds");
        }
        // 移除元素并将后面的元素向前移动
        for (int i = index; i < size - 1; i++) {
            elements[i] = elements[i + 1];
        }
        // 将最后一个元素置为空
        elements[--size] = null;
    }

    /**
     * 修改元素
     * @param index
     * @param element
     */
    public void set(int index, T element) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index out of bounds");
        }
        elements[index] = element;
    }

    /**
     * 随机访问元素
     * @param index
     * @return
     */
    public T get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index out of bounds");
        }
        return (T) elements[index];
    }

    /**
     * 获取元素个数
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 是否需要扩容
     */
    private void ensureCapacity() {
        if (size == elements.length) {
            int newCapacity = elements.length * 2;
            Object[] newElements = new Object[newCapacity];
            System.arraycopy(elements, 0, newElements, 0, size);
            elements = newElements;
        }
    }

}
